home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 6999 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.0 KB  |  90 lines

  1. Path: keats.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How to Display a File Backwards?
  5. Date: 16 Feb 1996 18:33:25 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Message-ID: <4g3eplINNo0k@keats.ugrad.cs.ubc.ca>
  8. References: <4g1rpl$kqo@newsbf02.news.aol.com>
  9. NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
  10.  
  11. In article <4g1rpl$kqo@newsbf02.news.aol.com>,
  12. ASCII zero <asciizero@aol.com> wrote:
  13. >Hello!
  14. >
  15. >What is the best way to display a text file backwards, using the standard
  16. >ANSI C functions, if the file is constantly appended/updated? 
  17.  
  18. This doesn't make that much sense. First of all, ANSI doesn't really specify
  19. that something _can_ be updating or appending to your file while your program
  20. is executing, does it?
  21.  
  22. What do you do if you have already started displaying the file and it gets
  23. appended to? Your question is pretty vague.
  24.  
  25. Here is a silly UNIX program that does it with memory maps:
  26.  
  27.  
  28. #include <sys/types.h>
  29. #include <sys/mman.h>
  30. #include <unistd.h>
  31. #include <fcntl.h>
  32. #include <stdio.h>
  33. #include <stddef.h>
  34. #include <errno.h>
  35.  
  36. int main(argc, argv)
  37. int argc;
  38. char **argv;
  39. {
  40.     int i;
  41.     int fd;
  42.     int size;
  43.     char *where;
  44.  
  45.     if (argc < 2) {
  46.         printf("program to reverse the contents of a file\n");
  47.         printf("usage: %s <file>\n",argv[0]);
  48.         exit(1);
  49.     }
  50.  
  51.     if ((fd = open(argv[1], O_RDWR)) < 0) {
  52.         perror(argv[1]);
  53.         exit(1);
  54.     }
  55.  
  56.  
  57.     /*
  58.      * get size of file
  59.      */
  60.  
  61.     size = lseek(fd, 0, SEEK_END);
  62.  
  63.     /*
  64.      * map file to virtual memory, so "where" points to the beginning
  65.      */
  66.  
  67.     where = (char *) mmap((caddr_t) 0, size, PROT_READ|PROT_WRITE,MAP_FILE|MAP_SHARED, fd, 0);
  68.  
  69.  
  70.     /*
  71.      * if mmap was successful, perform the reversal, else print
  72.      * error message
  73.      */
  74.  
  75.     if (where != (caddr_t)  -1)
  76.         for (i = 0; i < size/2; i++) {    /* do the reversal :)    */
  77.             char tmp = where[i];
  78.             where[i] = where[size-i-1];
  79.             where[size-i-1] = tmp;
  80.         }
  81.     else
  82.         perror("mmap() failed");
  83.  
  84.     munmap(where, size);
  85. }
  86.  
  87.  
  88. -- 
  89.  
  90.